'use strict';

/**
 * JWT token管理
 */
const jwt = require('jsonwebtoken');

const secretKey = require('../../config/secret').token_secret_key;
const secret = Buffer.from(secretKey, 'base64');
// 一般token过期策略
const TOKEN_EXPIRATION = '1h'; // 秒
// const TOKEN_EXPIRATION = 60 * 60; // 秒

exports.generateToken = function (payload) {
    const token = jwt.sign(payload, secret, {expiresIn: TOKEN_EXPIRATION});
    return token;
};

exports.verifyToken = function (token) {
    try {
        const payload = jwt.verify(token, secret);
        // 超时校验
        if (payload.exp > Date.now()) {
            return false;
        }
        return true;

    } catch (err) {
        return false;
    }
};

exports.decodeToken = function (token) {
    const payload = jwt.decode(token);
    return payload;
};

exports.refreshToken = function (token) {
    const payload = this.decodeToken(token);
    let tokenNew = null;
    if (payload) {
        tokenNew = jwt.sign({uid: payload.uid}, secret, {expiresIn: TOKEN_EXPIRATION});
    }

    return tokenNew;
};

exports.getToken = function (req) {
    if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { // Authorization: Bearer [token]
        return req.headers.authorization.split(' ')[1];
    } else if (req.query && req.query.token) {
        return req.query.token
    } else if (req.cookies && req.cookies.token) { // for page
        return req.cookies.token
    }
    return null
}
